package edu.ccut.saturn.studio.core.search.dialog;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.eclipse.core.resources.IProject;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.ui.dialogs.AbstractElementListSelectionDialog;

import edu.ccut.saturn.studio.Activator;
import edu.ccut.saturn.studio.Images;
import edu.ccut.saturn.studio.core.search.IObserver;
import edu.ccut.saturn.studio.core.search.SaturnFileSearcher;
import edu.ccut.saturn.studio.core.search.SaturnFileSearcher.SearchResult;
import edu.ccut.saturn.studio.core.util.eclipse.Messages;
import edu.ccut.saturn.studio.core.util.eclipse.SaturnSWTUtils;
import edu.ccut.saturn.studio.logic.model.IShapeSearcher;
import edu.ccut.saturn.studio.logic.model.Shape;
import edu.ccut.saturn.studio.naviagtor.SaturnFile;

public class OneCompontentSearchDialog extends AbstractElementListSelectionDialog {

	protected IShapeSearcher shapeSearcher;
	
	protected String suffix;
	protected IProject project;

	private List<SearchResult> resultInProject = new ArrayList<SearchResult>();
	
	private List<SearchResult> resultInWorkspace = new ArrayList<SearchResult>();

	public OneCompontentSearchDialog(Shell parent, IShapeSearcher shapeSearcher) {
		super(parent, new SaturnSWTUtils.SaturnLabelDefaultProvider() {

			@Override
			public Image getImage(Object element) {
				if (element instanceof SearchResult) {
					SearchResult result = (SearchResult) element;

					String fileName = result.getFileName();
					int index = fileName.lastIndexOf("."); //$NON-NLS-1$

					if (index >= 0 && index < fileName.length()) {
						String suffix = fileName.substring(index + 1);

						return SaturnFile.getImageFromFileType(suffix);
					}
				}
				return super.getImage(element);
			}
		});
		
		this.shapeSearcher = shapeSearcher;
	}
	
	public OneCompontentSearchDialog(Shell parent, String suffix, IProject project ) {
		super(parent, new SaturnSWTUtils.SaturnLabelDefaultProvider() {

			public Image getImage(Object element) {
				if (element instanceof SearchResult) {
					SearchResult result = (SearchResult) element;

					String fileName = result.getFileName();
					int index = fileName.lastIndexOf("."); //$NON-NLS-1$

					if (index >= 0 && index < fileName.length()) {
						String suffix = fileName.substring(index + 1);

						return SaturnFile.getImageFromFileType(suffix);
					}
				}
				return super.getImage(element);
			}
		});
		this.suffix = suffix;
		this.project = project;
	}

	public OneCompontentSearchDialog(Shell parent, ILabelProvider renderer,
			Shape shape) {
		super(parent, renderer);
		this.shapeSearcher = shape;
	}

	protected Point getInitialSize() {
		return new Point(600, 500);
	}

	protected void computeResult() {
		setResult(Arrays.asList(getSelectedElements()));
	}

	protected Control createDialogArea(Composite parent) {
		getShell().setText(Messages.getString("OneCompontentSearchDialog.ChooseKeyValue")); //$NON-NLS-1$
		Composite contents = (Composite) super.createDialogArea(parent);
		createSearch(contents);
		createFilterText(contents);
		createFilteredList(contents);
		createMessageArea(contents);
		setListElements(new String[] { "" }); //$NON-NLS-1$
		setSelection(getInitialElementSelections().toArray());

		return contents;
	}

	protected Text createJarPathText(Composite parent) {

		Text text = new Text(parent, SWT.BORDER | SWT.READ_ONLY);

		GridData data = new GridData();
		data.grabExcessVerticalSpace = false;
		data.grabExcessHorizontalSpace = true;
		data.horizontalAlignment = GridData.FILL;
		data.verticalAlignment = GridData.BEGINNING;
		text.setLayoutData(data);
		text.setFont(parent.getFont());

		return text;
	}

	private Composite createSearch(Composite parent) {
		MenuItem projectMenuItem;
		MenuItem AllMenuItem;
		final Composite composite = new Composite(parent, SWT.NONE);
		final GridData gd_composite = new GridData(SWT.FILL, SWT.FILL, true,
				false);
		gd_composite.heightHint = 28;
		composite.setLayoutData(gd_composite);
		composite.setLayout(new FormLayout());

		final Label label = new Label(composite, SWT.NONE);
		final FormData fd_label = new FormData();
		fd_label.bottom = new FormAttachment(0, 24);
		fd_label.top = new FormAttachment(16);
		fd_label.right = new FormAttachment(0, 27);
		fd_label.left = new FormAttachment(0, 2);
		label.setLayoutData(fd_label);
		label.setText("Key"); //$NON-NLS-1$

		final ToolBar toolBar = new ToolBar(composite, SWT.FLAT);
		final FormData fd_toolBar = new FormData();
		fd_toolBar.top = new FormAttachment(0);
		fd_toolBar.right = new FormAttachment(100);
		toolBar.setLayoutData(fd_toolBar);
		final ToolItem projectToolItem = new ToolItem(toolBar, SWT.DROP_DOWN);
		projectToolItem.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				if (e.detail == 0) {
					setListElements(resultInProject.toArray());
				}
			}
		});

		projectToolItem.setImage(Activator.getImage(Images.AMPLIFY_PLUS));
		final Menu menu = new Menu(toolBar);
		addDropDown(projectToolItem, menu);
		projectMenuItem = new MenuItem(menu, SWT.NONE);
		projectMenuItem.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				setListElements(resultInProject.toArray());
			}
		});
		projectMenuItem.setText(Messages.getString("OneCompontentSearchDialog.0")); //$NON-NLS-1$
		AllMenuItem = new MenuItem(menu, SWT.NONE);
		AllMenuItem.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				if (resultInWorkspace.isEmpty()) {
					startThreadWordspace();
				} else {
					setListElements(resultInWorkspace.toArray());
				}
			}
		});
		AllMenuItem.setText(Messages.getString("OneCompontentSearchDialog.1")); //$NON-NLS-1$
		startThreadProject();
		return composite;
	}

	private static void addDropDown(final ToolItem item, final Menu menu) {
		item.addListener(SWT.Selection, new Listener() {
			public void handleEvent(Event event) {
				if (event.detail == SWT.ARROW) {
					Rectangle rect = item.getBounds();
					Point pt = new Point(rect.x, rect.y + rect.height);
					pt = item.getParent().toDisplay(pt);
					menu.setLocation(pt.x, pt.y);
					menu.setVisible(true);
				}
			}
		});
	}

	protected void startThreadProject() {
		new Thread(new Runnable() {
			public void run() {
				IObserver observer = new IObserver() {
					public synchronized void update(final List<SearchResult> files) {
						Display.getDefault().asyncExec(new Runnable() {
							public void run() {
								resultInProject = files;
								setListElements(files.toArray());
							}
						});
					}
				};
				
				if (shapeSearcher != null) {
					shapeSearcher.keyMapInProject(observer);
				} else {
					try {
						SaturnFileSearcher.getValueAndDocumentMapInProject(project, suffix, observer, null);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
	}

	protected void startThreadWordspace() {
		new Thread(new Runnable() {
			public void run() {
				IObserver observer = new IObserver() {
					public synchronized void update(final List<SearchResult> files) {
						Runnable runnable = new Runnable() {
							public void run() {
								resultInWorkspace = files;
								setListElements(files.toArray());
							}
						};
						Display.getDefault().asyncExec(runnable);
					}
				};
				
				if (shapeSearcher != null) {
					shapeSearcher.keyMapInWorkspace(observer);
				} else {
					try {
						SaturnFileSearcher.getValueAndDocumentMapInWorkspace(suffix, observer, null);
					} catch (Exception e) {
						e.printStackTrace();
					}		
				}
			}
		}).start();
	}

	protected void configureShell(Shell newShell) {
		super.configureShell(newShell);
		newShell.setImage(Activator.getImage(Images.SATURN_ICONS_SMALLNAME));
	}
}